<template>
  <!-- 动态渲染 Drawer 或 Dialog -->
  <component
    :is="componentType === 'dialog' ? 'el-dialog' : 'el-drawer'"
    v-model="localVisible"
    :title="title"
    :size="componentType === 'drawer' ? drawerSize : undefined"
    :width="componentType === 'dialog' ? dialogWidth : undefined"
    :custom-class="customClass"
    :before-close="beforeClose"
    @close="handleClose"
  >
    <!-- 渲染传入的子组件 -->
    <component :is="customContent" v-model:formModel="localFormModel" />

    <!-- 弹窗的 footer -->
    <template v-if="showFooter" #footer>
      <div :style="{ textAlign: footerAlign }">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </template>
  </component>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from "vue";
import { ElDrawer, ElDialog, ElButton } from "element-plus";

// 定义 props 和 emit 事件
const props = defineProps<{
  visible: boolean; // 父组件控制 visible 状态
  title: string;
  componentType: "dialog" | "drawer";
  formModel: Record<string, any>;
  customContent: Object | Function;
  drawerSize?: string;
  dialogWidth?: string;
  customClass?: string;
  beforeClose?: (done: () => void) => void;
  showFooter?: boolean; // 是否显示 footer
  footerAlign?: "left" | "center" | "right"; // footer 对齐方式
}>();

const emit = defineEmits<{
  (e: "submit", formModel: Record<string, any>): void;
  (e: "close"): void;
  (e: "update:visible", value: boolean): void;
}>();

// 本地 visible，用于控制弹窗或抽屉的显示
const localVisible = ref(props.visible);

// 本地 formModel 副本，用于双向绑定
const localFormModel = ref({ ...props.formModel });

// 监听外部 visible 的变化，更新本地的 localVisible
watch(
  () => props.visible,
  newVal => {
    localVisible.value = newVal;
  }
);

// 监听 localVisible 的变化，通知父组件更新 visible
watch(
  () => localVisible.value,
  newVal => {
    emit("update:visible", newVal);
  }
);

// 监听外部 formModel 的变化，更新本地副本
watch(
  () => props.formModel,
  newVal => {
    localFormModel.value = { ...newVal };
  },
  { deep: true, immediate: true }
);

// 关闭弹窗的处理
const handleClose = () => {
  localVisible.value = false; // 关闭弹窗
  emit("close");
};

// 提交表单的处理
const handleSubmit = () => {
  emit("submit", localFormModel.value); // 提交表单的副本
  handleClose();
};
</script>
